import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/components/product_price.dart';
import 'package:mall/core/models/store_product_query.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/screens/product/product_page.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

/// 商品列表
class ProductList extends StatefulWidget {
  final int storeId;
  final int categoryId;
  final int areaId;
  final String queryKey;

  const ProductList({
    Key key,
    @required this.storeId,
    this.categoryId,
    this.areaId,
    this.queryKey,
  }) : super(key: key);

  @override
  _ProductListState createState() => _ProductListState();
}

class _ProductListState extends State<ProductList> {
  RefreshController _refreshController;
  int _pageIndex;
  StoreProductQuery _storeProductQuery;
  final List<Product> _list = [];

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: true);
  }

  @override
  void dispose() {
    _refreshController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: _refreshController,
      enablePullUp: _storeProductQuery != null && _storeProductQuery.productList.length == 10,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: SingleChildScrollView(
        padding: EdgeInsets.all(8.w),
        child: Wrap(
          spacing: 8.w,
          runSpacing: 8.w,
          children: List.generate(
            _list.length,
            (index) => _buildItem(_list[index]),
          ),
        ),
      ),
    );
  }

  Widget _buildItem(Product product) {
    return GestureDetector(
      onTap: () => _onTapItem(product),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.w),
        ),
        width: ((375 - 8 * 3) ~/ 2).w,
        height: 240.w,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.vertical(
                    top: Radius.circular(4.w),
                  ),
                  child: ImageNetwork(
                    url: "${product.productImage}",
                    width: ((375 - 8 * 3) ~/ 2).w,
                    height: ((375 - 8 * 3) ~/ 2).w,
                  ),
                ),
                Positioned(
                  top: 13.w,
                  right: 0.w,
                  child: _buildAreaTag(product.storeAreaNames),
                )
              ],
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(4.w, 4.w, 4.w, 0),
              child: Text(
                "${product.productName}",
                style: TextStyle(fontSize: 12.w),
                maxLines: 2,
              ),
            ),
            Spacer(),
            Padding(
              padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 4.w),
              child: ProductPrice(list: product.priceVos),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建商区标签
  Widget _buildAreaTag(String areaName) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: Theme.of(context).primaryColor,
        borderRadius: BorderRadius.horizontal(left: Radius.circular(10.w)),
      ),
      height: 20.w,
      child: Center(
        child: Text(
          "$areaName",
          style: TextStyle(color: Colors.white, fontSize: 12.sp),
        ),
      ),
    );
  }

  void _onTapItem(Product product) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => ProductPage(
          args: ProductPageArgs(null, product.productId, product.miaId, product.curStoreId),
        ),
      ),
    );
  }

  /// 第一页
  void _onRefresh() async {
    _pageIndex = 0;
    final api = context.read<Api>();
    try {
      final storeProductQuery = await api.storeProductQueryNew(
        widget.storeId,
        widget.categoryId,
        widget.areaId,
        widget.queryKey,
        _pageIndex,
        null,
      );
      if (!mounted) {
        return;
      }
      _refreshController.refreshCompleted();
      setState(() {
        _storeProductQuery = storeProductQuery;
        _list.clear();
        _list.addAll(storeProductQuery.productList);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.refreshFailed();
      EasyLoading.showToast("${e.message}");
    } catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.refreshFailed();
      EasyLoading.showToast("$e");
    }
  }

  /// 更多页
  void _onLoading() async {
    _pageIndex++;
    final api = context.read<Api>();
    try {
      final storeProductQuery = await api.storeProductQueryNew(
        widget.storeId,
        widget.categoryId,
        widget.areaId,
        widget.queryKey,
        _pageIndex,
        null,
      );
      if (!mounted) {
        return;
      }
      _refreshController.loadComplete();
      setState(() {
        _storeProductQuery = storeProductQuery;
        _list.addAll(storeProductQuery.productList);
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.loadFailed();
      EasyLoading.showToast("${e.message}");
    }
  }
}
